<?php

namespace app\admin\controller\cashcard;

use app\admin\model\CashcardCate;
use app\admin\model\ShopCate;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemBranch;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * Class Cate 代金券分组
 * @package app\admin\controller\cashcard
 * @ControllerAnnotation(title="cashcard_cate")
 */
class Cate extends AdminController
{

    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = CashcardCate::init();

    }

    /**
     * @author FashionJune
     */
    public function get_card_type()
    {
        $list = arr2id_title($this->model->getCardType());
        $this->success(null, $list);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = $this->model
                ->where($where)
                ->with(['cards', 'admin'])
//                ->withJoin(['cards', 'admin'], 'LEFT')
                ->count();
            $list = $this->model
                ->where($where)
                ->with([
                    'cards' => function ($query) {
                        $query->field(['id', 'cate_id', 'code', 'to_user', 'to_admin', 'status']);
                    },
                    'admin' => function ($query) {
                        $query->field(['id', 'username']);
                    },
//                    'branch' => function ($query) {
//                        $query->field('id', 'name');
//                    }
                ])
//                ->withJoin([
//                    'cards' => ['id', 'cate_id', 'code' , 'to_user', 'to_admin', 'status'],
//                    'admin' => ['id', 'username']
//                ], 'LEFT')
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="添加")
     * @param mixed $id
     * @return mixed
     */
    public function add($id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'card_type|类型' => 'require',
                'expire_time|过期时间' => 'require',
                'num|数量' =>'require|between:1,1000',
            ];
            $this->validate($post, $rule);
            if (strtotime($post['expire_time']) < strtotime('tomorrow')) {
                $this->error('请至少选择第二天过期');
            } else {
                $post['expire_time'] .= ' 23:59:59';
            }
            $post['expire_time'] = strtotime($post['expire_time']);
            if (!empty($post['card_author'])) {
                $post['card_author'] = arr2str(array_keys($post['card_author']));
            } else {
                $post['card_author'] = '';
            }
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败，' . $e->getMessage());
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $cate_list = ShopCate::init()->getCateList();
        $branch_list = SystemBranch::init()->getGroupList();
        $this->assign([
            'id' => $id,
            'cate_list' => $cate_list,
            'branch_list' => $branch_list,
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'num|数量' => 'require|between:' . $row['send_num'] . ',1000',
            ];
            $this->validate($post, $rule);
            try {
                $before = $row['num'];
                $save = $row->save($post);
                if ($post['num'] && ((int)$post['num'] != (int)$before)) {
                    $this->model->updateCardNum($id, $before);
                }
            } catch (\Exception $e) {
                $this->error('保存失败' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="授权")
     * @return mixed
     * @author FashionJune
     */
    public function cardAuthorize($cate_id)
    {
        $row = $this->model->find($cate_id);
        if ($this->request->isAjax()) {
            $data = $this->request->except(['__token', 'file']);
            if ($data['num_person'] != $row['num_person']) {
                $update['num_person'] = $data['num_person'];
            }
            if (!empty($data['card_author'])) {
                $update['card_author'] = arr2str(array_keys($data['card_author']));
            } else {
                $update['card_author'] = '';
            }
            try {
                $save = $row->save($update);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
//        $admin_list = SystemAdmin::init()->getAdminList(['id', 'username', 'remark']);
        $branch_list = SystemBranch::init()->getGroupList();
        $author_list = str2arr($row->card_author ?? '');
        foreach ($branch_list as &$group) {
            $group['checked'] = false;
            foreach ($group['admins'] as &$admin) {
                $admin['checked'] = in_array($admin['id'], $author_list);
                $admin['checked'] && ($group['checked'] = true);
            }
        }

        $with = ['branch_list' => $branch_list, 'row' => $row];
        return $this->fetch('', $with);
    }


}